<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="公司名称" prop="companyId">
          <el-select v-model="queryParams.companyId" placeholder="请选择下拉选择" filterable clearable
            :style="{width: '100%'}">
            <el-option v-for="(item, index) in companyList"
              :key="index"
              :label="item.companyName"
              :value="item.companyId"/>
          </el-select>
        </el-form-item>
      <el-form-item label="邮件主题" prop="emailTheme">
        <el-input
          v-model="queryParams.emailTheme"
          placeholder="请输入邮件主题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker clearable
          v-model="queryParams.startTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择开始时间" style="width: 160px;">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker clearable
          v-model="queryParams.endTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:easy:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:easy:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:easy:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:easy:export']"
        >导出</el-button>
      </el-col>
        <audio controls="controls" hidden src="../voice/zhendong.mp3" ref="audio1"></audio>
        <audio controls="controls" hidden src="../voice/tips.mp3" ref="audio2"></audio>
        <audio controls="controls" hidden src="../voice/delete.mp3" ref="audio3"></audio>
        <audio controls="controls" hidden src="../voice/Download.mp3" ref="audio4"></audio>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="easyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="易告知编号" align="center" type="index" width="105"/>
      <el-table-column label="公司名称" align="center" prop="companyName" :show-overflow-tooltip="true"/>
      <el-table-column label="邮件主题" align="center" prop="emailTheme" :show-overflow-tooltip="true"/>
      <el-table-column label="邮件内容" align="center" prop="emailContent" :show-overflow-tooltip="true"/>
      <el-table-column label="发送间隔" align="center" prop="sendInterval" />
      <el-table-column label="开始时间" align="center" prop="startTime" width="180" sortable>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180" sortable>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:easy:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:easy:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['system:easy:query']"
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改易告知对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="公司名称" prop="companyId">
          <el-select v-model="form.companyId" placeholder="请选择下拉选择" filterable clearable
            :style="{width: '100%'}">
            <el-option v-for="(item, index) in companyList"
              :key="index"
              :label="item.companyName"
              :value="item.companyId"/>
          </el-select>
        </el-form-item>
        <el-form-item label="邮件主题" prop="emailTheme">
          <el-input v-model="form.emailTheme" placeholder="请输入邮件主题" />
        </el-form-item>
        <el-form-item label="邮件内容" prop="emailContent">
          <el-input v-model="form.emailContent" :min-height="192" type="textarea"/>
        </el-form-item>
        <el-form-item label="发送间隔" prop="sendInterval">
              <el-input v-model="form.sendInterval" placeholder="请输入cron执行表达式">
                <template slot="append">
                  <el-button type="primary" @click="handleShowCron">
                    生成表达式
                    <i class="el-icon-time el-icon--right"></i>
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable
            v-model="form.startTime"
            type="date"
            value-format="yyyy-MM-dd"
            :picker-options="startDatePicker"
            placeholder="请选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker clearable
            v-model="form.endTime"
            type="date"
            value-format="yyyy-MM-dd"
            :picker-options="endDatePicker"
            placeholder="请选择结束时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="Cron表达式生成器" :visible.sync="openCron" append-to-body destroy-on-close class="scrollbar">
      <crontab @hide="openCron=false" @fill="crontabFill" :expression="expression"></crontab>
    </el-dialog>

    <!-- 查看详情 -->
    <el-dialog title="查看详情" :visible.sync="openView" width="700px" append-to-body>
      <el-form ref="form" :model="form" label-width="120px" size="mini">
        <el-row>
          <el-col :span="12">
            <el-form-item label="公司名称：">{{ form.companyName }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮件主题：">{{ form.emailTheme }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="邮件内容：">{{ form.emailContent }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发送间隔：">{{ form.sendInterval }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始时间：">{{ form.startTime }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间：">{{ form.endTime }}</el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="openView = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listEasy, getEasy, delEasy, addEasy, updateEasy } from "@/api/system/easy";
import {companyList} from "@/api/system/company";
import Crontab from '@/components/Crontab';
export default {
  components: { Crontab },
  name: "Easy",
  data() {
    return {
      startDatePicker: this.beginDate(),
      endDatePicker: this.processDate(),
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 易告知表格数据
      easyList: [],
      //公司表格数据
      companyList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示详细弹出层
      openView: false,
      // 是否显示Cron表达式弹出层
      openCron: false,
      // 传入的表达式
      expression: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyId: null,
        emailContent: null,
        emailTheme: null,
        sendInterval: null,
        startTime: null,
        endTime: null,
        fakeDelete: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        emailTheme: [
          { required: true, message: "邮件主题不能为空", trigger: "blur" },
          { min: 2, max: 60, message: '发布名称长度必须介于 2 和 60 之间', trigger: 'blur' }
        ],
        companyId:[
        { required: true, message: "公司名称不能为空", trigger: "blur" }
        ],
        sendInterval: [
          { required: true, message: "cron执行表达式不能为空", trigger: "blur" },
        ],
        startTime: [
          { required: true, message: "开始时间不能为空", trigger: "blur" },
        ],
        endTime: [
          { required: true, message: "结束时间不能为空", trigger: "blur" },
        ],

      }
    };
  },
  created() {
    this.getList();
    this.getCompany();
  },
  methods: {
    beginDate(){
      const self = this
      return {
        disabledDate(time){
          if (self.form.endTime) {  //如果结束时间不为空，则小于结束时间
            return new Date(self.form.endTime).getTime() < time.getTime()
          } else {
            return time.getTime() < Date.now()-86400000//开始时间不选时，结束时间最大值小于等于当天
          }
        }
      }
    },
    processDate() {
      const  self = this
      return {
        disabledDate(time) {
          if (self.form.startTime) {  //如果开始时间不为空，则结束时间大于开始时间
            return new Date(self.form.startTime).getTime() > time.getTime()
          } else {
            return time.getTime() < Date.now()//开始时间不选时，结束时间最大值小于等于当天
          }
        }
      }
    },
    /** 任务详细信息 */
    handleView(row) {
      this.$refs.audio2.currentTime=0;
      this.$refs.audio2.play();
      getEasy(row.easyId).then(response => {
        this.form = response.data;
        this.openView = true;
      });
    },
    /** cron表达式按钮操作 */
    handleShowCron() {
      this.expression = this.form.sendInterval;
      this.openCron = true;
    },
    /** 确定后回传值 */
    crontabFill(value) {
      this.form.sendInterval = value;
    },
    /** 查询易告知列表 */
    getList() {
      this.loading = true;
      listEasy(this.queryParams).then(response => {
        this.easyList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getCompany(){
      companyList().then(response => {
        this.companyList = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        easyId: null,
        companyId: null,
        emailContent: null,
        emailTheme: null,
        sendInterval: null,
        startTime: null,
        endTime: null,
        fakeDelete: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.easyId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加易告知";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$refs.audio2.currentTime=0;
      this.$refs.audio2.play();
      this.reset();
      const easyId = row.easyId || this.ids
      getEasy(easyId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改易告知";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.easyId != null) {
            updateEasy(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addEasy(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$refs.audio3.currentTime=0;
      this.$refs.audio3.play();
      const easyIds = row.easyId || this.ids;
      this.$modal.confirm('是否确认删除易告知id为"' + easyIds + '"的数据项？').then(function() {
        return delEasy(easyIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.$refs.audio4.currentTime=0;
      this.$refs.audio4.play();
      this.download('system/easy/export', {
        ...this.queryParams
      }, `easy_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
